package com.nami.web.facade.impl;

import cn.hutool.core.collection.CollUtil;
import com.nami.store.api.request.message.HisMsgQryRequest;
import com.nami.store.api.service.RemoteGroupMemberService;
import com.nami.store.api.service.RemoteGroupService;
import com.nami.store.api.service.RemoteMessageService;
import com.nami.store.api.service.RemoteUserService;
import com.nami.store.api.response.user.UserDTO;
import com.nami.store.api.response.group.GroupDTO;
import com.nami.store.api.response.groupmember.GroupMemberDTO;
import com.nami.store.api.response.message.MessageDTO;
import com.nami.web.convert.GrpConvert;
import com.nami.web.convert.MsgConvert;
import com.nami.web.convert.UserConvert;
import com.nami.web.dto.msg.MsgQryDTO;
import com.nami.web.facade.MsgFacadeService;
import com.nami.web.vo.msg.HisMsg;
import com.nami.web.vo.msg.MessageInfoVO;
import com.nami.web.vo.user.UserInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.json.utils.JsonUtils;
import org.dromara.common.satoken.utils.LoginHelper;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class MsgFacadeServiceImpl implements MsgFacadeService {

    @DubboReference
    RemoteMessageService messageService;

    @DubboReference
    RemoteUserService userService;

    @DubboReference
    RemoteGroupService groupService;

    @DubboReference
    RemoteGroupMemberService groupMemberService;

    @Override
    public HisMsg qryHisMsgs(MsgQryDTO dto) {
        log.info("[message] 查询历史消息 request={}", JsonUtils.toJsonString(dto));
        String appKey = LoginHelper.getAppKey();
        HisMsgQryRequest request = new HisMsgQryRequest();
        request.setAppKey(appKey);
        request.setConverId(buildConverId(dto));
        request.setLastSeq(dto.getLastSeq());
        if (dto.getLastSeq() == 0) {
            request.setLastSeq(null);
        }
        request.setPageSize(dto.getPageSize());
        HisMsg result = new HisMsg();
        switch (dto.getConverType()) {
            case 1:
                List<MessageDTO> privateHisMsgs = messageService.getPrivateHisMsgs(request);
                if (CollUtil.isNotEmpty(privateHisMsgs)) {
                    result.setMessages(MsgConvert.INSTANCE.convertList(privateHisMsgs));
                    UserDTO user = userService.getUserByUserId(dto.getTargetId());
                    result.setTargetUserInfo(UserConvert.INSTANCE.convert(user));
                }
                break;
            case 2:
                List<MessageDTO> grpMsgs = messageService.getGrpHisMsgs(request);
                if (CollUtil.isNotEmpty(grpMsgs)) {
                    List<MessageInfoVO> msgs = MsgConvert.INSTANCE.convertList(grpMsgs);
                    Set<String> userIds = msgs.stream().map(MessageInfoVO::getSenderId).collect(Collectors.toSet());

                    // 2025-1-7 此处需要缓存数据。或缓存到redis 改变remote方法逻辑
                    // TODO
                    Map<String, GroupMemberDTO> membMap = groupMemberService.getGrpMembsByUserIds(dto.getTargetId(), List.copyOf(userIds));

                    Map<String, UserDTO> userMap = userService.getUsersByUserIds(List.copyOf(userIds));
                    for (MessageInfoVO msg : msgs) {
                        UserDTO userDTO = userMap.get(msg.getSenderId());
                        if (userDTO != null) {
                            UserInfoVO userInfo = UserConvert.INSTANCE.convert(userDTO);
                            GroupMemberDTO groupMemberDTO = membMap.get(userInfo.getUserId());
                            if (groupMemberDTO != null) {
                                userInfo.setNick(groupMemberDTO.getNickName());
                            }
                            msg.setSenderInfo(userInfo);
                        }
                    }
                    result.setMessages(msgs);
                    GroupDTO groupInfo = groupService.getGroupInfo(dto.getTargetId());
                    result.setGroupInfo(GrpConvert.INSTANCE.convert(groupInfo));
                }
                break;
            default:
                break;
        }
        return result;
    }

    private String buildConverId(MsgQryDTO dto) {
        if (dto.getConverType() == 1) {
            String[] ids = {dto.getUserId(), dto.getTargetId()};
            Arrays.sort(ids, Comparator.naturalOrder());
            return "si_" + ids[0] + "_" + ids[1];
        }
        return dto.getTargetId();
    }

}
